import { createAdminUserVerify } from '~/server/validation';
import { AdminUser, AdminUserModel } from '~/server/models/admin_user.model';
import { AdminPermissionModel } from '~/server/models/admin_permission.model';
import { checkAdminUserPermission } from '~/server/utils/util.permissionVerification';

/**
 * @api {put} /admin/user/create 创建后台管理员用户
 * @apiName 创建后台管理员用户
 * @apiGroup 后台管理员用户
 * @apiDescription 创建后台管理员用户
 *
 * @apiPermission admin
 *
 * @apiSampleRequest /admin/user/create
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {Object} user 用户信息
 * @apiBody {String} user.avatar 头像
 * @apiBody {String} user.nickname 昵称
 * @apiBody {String} user.username 用户名
 * @apiBody {String} user.password 密码
 * @apiBody {String} user.permission 权限
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '创建成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, 'admin');
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const body: any = await readBody(event);

		const user: AdminUser = body.user || {}; // 用户信息

		// 参数校验
		const validation: string | undefined = createAdminUserVerify.validate({ ...user }).error
			?.message;
		if (validation && validation !== void 0) {
			return {
				code: 0,
				message: validation,
			};
		}

		// 查找用户是否存在
		const findResult = await AdminUserModel.findOne({
			username: user.username,
		});
		if (findResult !== null) {
			return {
				code: 0,
				message: '用户名已存在',
			};
		}

		// 验证权限是否存在
		const permissionFindResult = await AdminPermissionModel.findOne({
			name: user.permission,
		});
		if (permissionFindResult === null) {
			return {
				code: 0,
				message: '权限不存在',
			};
		}

		// 创建用户
		await AdminUserModel.create({
			...user,
			password: sha256(md5(user.password)),
		});
		return {
			code: 1,
			message: '创建成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
